import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import '../models/expense.dart';
import '../services/database_service.dart';
import 'month_detail_screen.dart';

class HistoryScreen extends StatefulWidget {
  const HistoryScreen({Key? key}) : super(key: key);

  @override
  _HistoryScreenState createState() => _HistoryScreenState();
}

class _HistoryScreenState extends State<HistoryScreen> {
  final DatabaseService _databaseService = DatabaseService();
  List<Map<String, dynamic>> _monthlyData = [];

  @override
  void initState() {
    super.initState();
    _loadMonthlyData();
  }

  Future<void> _loadMonthlyData() async {
    final expenses = await _databaseService.getExpenses();
    final Map<String, double> monthlyTotals = {};

    for (var expense in expenses) {
      final monthKey = DateFormat('yyyy-MM').format(expense.date);
      monthlyTotals[monthKey] = (monthlyTotals[monthKey] ?? 0) + expense.amount;
    }

    setState(() {
      _monthlyData = monthlyTotals.entries.map((entry) {
        return {
          'month': entry.key,
          'total': entry.value,
        };
      }).toList()
        ..sort(
            (a, b) => (b['month'] as String).compareTo(a['month'] as String));
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('历史记录'),
        centerTitle: true,
      ),
      body: _monthlyData.isEmpty
          ? const Center(
              child: Text(
                '暂无历史记录',
                style: TextStyle(fontSize: 16),
              ),
            )
          : ListView.builder(
              itemCount: _monthlyData.length,
              itemBuilder: (context, index) {
                final data = _monthlyData[index];
                final date = DateFormat('yyyy-MM').parse(data['month']);
                return Card(
                  margin:
                      const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                  child: ListTile(
                    title: Text(
                      DateFormat('yyyy年MM月').format(date),
                      style: const TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    trailing: Text(
                      '¥${data['total'].toStringAsFixed(2)}',
                      style: const TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                        color: Colors.red,
                      ),
                    ),
                    onTap: () {
                      Navigator.push(
                        context,
                        MaterialPageRoute(
                          builder: (context) => MonthDetailScreen(
                            month: date,
                          ),
                        ),
                      );
                    },
                  ),
                );
              },
            ),
    );
  }
}
